/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.device;

import com.cxhd.lis.util.DateUtil;
import com.cxhd.lis.util.Tool;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sun.misc.BASE64Decoder;

/**
 *
 * @author 52461
 */
public class BC_5000 {

    private String baseData;
    private String base2Data;
    private String device_code = "BC-5000";
    private String code = "LA5";
    private String sampletype = "全血";
    private String sampletypeId = null;

    public BC_5000(String baseData) {
        this.baseData = baseData;

        parseComData();

    }

    public void getSampleTypeId() {
        try {
            sampletypeId = Db.findFirst("select * from lis_sampletype where SAMPLEDESCRIBE='" + sampletype + "'").get("PK") + "";

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void parseComData() {
        try {
            String sampleNo = null;
            String testDate = null;
            String testTime = null;
            System.out.println(baseData);
            Map<String, String> resultMap = new HashMap<String, String>();
            String ds[] = baseData.split("OBX");
           

 System.out.println(ds[0]+"********************************");
            String sampleInfo[] = ds[0].split("OBR")[1].replaceAll("\\|{1,}", "@").split("@");
            
                         for (int i = 0; i < sampleInfo.length; i++) {
                
              System.out.println(sampleInfo[i]+"********************************"+i);
                 
             }
            sampleNo = sampleInfo[2];
            testDate = DateUtil.getNumToDate(sampleInfo[4]);
            System.out.println(sampleInfo[2]+"----"+sampleInfo[4]+"---------"+testDate);

            for (int i = 0; i < ds.length; i++) {
                // System.out.println(i);
                if (i > 0) {
                    String test = ds[i].split("\\|")[3];
                    String testId = ds[i].split("\\|")[3].split("\\^")[1];
                    if (test.indexOf("RBC Histogram. BMP^99MRC") > 0) {
                        resultMap.put("image#RBC", encodeBase64(ds[i].split("\\|")[5].split("\\^")[4]));
                    } else if (test.indexOf("PLT Histogram. BMP^99MRC") > 0) {
                        resultMap.put("image#PLT", encodeBase64(ds[i].split("\\|")[5].split("\\^")[4]));
                    } else if (test.indexOf("WBC Histogram. BMP^99MRC") > 0) {
                        resultMap.put("image#WBC", encodeBase64(ds[i].split("\\|")[5].split("\\^")[4]));
                    } else if (test.indexOf("WBC DIFF Scattergram. BMP^99MRC") > 0) {
                        resultMap.put("image#DIFF", encodeBase64(ds[i].split("\\|")[5].split("\\^")[4]));
                    } else {
                        resultMap.put(testId.replace("*", ""), ds[i].split("\\|")[5]);
                    }
                }
            }
            sendDb(Tool.getSampleNo(code, sampleNo), testDate, resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据不完整解析错误");
        }
    }

    public void sendDb(String sampleNo, String datetime, Map<String, String> result) {

        System.out.println(sampleNo + "  " + datetime);
        // System.out.println(result);

        for (String key : result.keySet()) {
            try {
                System.out.println("保存到数据库" + key);
                makeInsertSqlInsert(tranMap(sampleNo, datetime, key, result.get(key)), "lis_testresult");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    //转换数据结构
    public Map<String, String> tranMap(String sampleNo, String datetime, String key, String value) {
        try {
            Map<String, String> newMap = new HashMap<String, String>();
           
            Record rs = Db.findFirst("select * from pp_device_test where TESTID='" + key.trim().replace("*", "") + "' AND DEVICEID='"+device_code+"'  limit 1");
            if (rs != null) {
                
                newMap.put("ITEMPK", rs.get("TESTPK") + "");
                newMap.put("TESTID", rs.get("TESTID") + "");
                newMap.put("UNIT", rs.get("UNIT") + "");
                newMap.put("SAMPLENO", sampleNo);

                if (rs.getStr("TESTID").equalsIgnoreCase("image#DIFF")||rs.getStr("TESTID").equalsIgnoreCase("image#RBC") || rs.getStr("TESTID").equalsIgnoreCase("image#PLT")||rs.getStr("TESTID").equalsIgnoreCase("image#WBC")) {
                  
                    newMap.put("RESULTFLAG", "2");//base64
                    // System.out.println("yyyyyyyyyy-----------------------");
                } else {
                    newMap.put("RESULTFLAG", "0");
                }
                newMap.put("TESTRESULT", value);
                newMap.put("MEASURETIME", datetime);
                newMap.put("DEVICEID", device_code);
                newMap.put("SAMPLETYPE", "16");
                newMap.put("UUID", Tool.string2MD5(datetime.trim() + sampleNo.trim() + device_code));
                return newMap;

            }
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //构建sql
    private boolean makeInsertSqlInsert(Map<String, String> map, String tableName) throws Exception {

        if (map == null) {
            return false;
        }

        String sql = "";
        StringBuilder sqlHead = new StringBuilder();
        StringBuilder sqlvalue = new StringBuilder();
        int index = 0;
        String[] values = new String[map.size()];
        sqlHead.append("insert into ").append(tableName).append(" (");
        sqlvalue.append(" values (");
        for (String key : map.keySet()) {
            values[index] = map.get(key);
            index++;
            if (index == map.size()) {
                sqlHead.append("`").append(key).append("`").append(" )");
                sqlvalue.append(map.get(key) == null ? "null)" : "'" + map.get(key) + "')");
                // map.get(key)==null?"":"";
                // sqlvalue.append("? )");
            } else {
                sqlHead.append("`").append(key).append("`").append(" , ");
                sqlvalue.append(map.get(key) == null ? "null," : "'" + map.get(key) + "',");
                //sqlvalue.append("?,");
            }

        }
        sql = sqlHead.append(sqlvalue).toString();
        //System.out.println(sqlHead.append(sqlvalue).toString()+"  "+values.length);
        //logger.info(sql);
        try {
            Db.update(sql);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return true;

    }

 

    public static String encodeBase64(String data) {
         return data;
       
//        StringBuffer sb = new StringBuffer();
//
//        BASE64Decoder decoder = new BASE64Decoder();
//        try {
//            //Base64解码
//            byte[] b = decoder.decodeBuffer(data);
//            for (int i = 0; i < b.length; ++i) {
//                if (b[i] < 0) {//调整异常数据
//                    // b[i]+=256;
//                    sb.append(b[i] + 256).append(" ");
//                } else {
//                    sb.append(b[i]).append(" ");
//                }
//                // System.out.println(b[i]);
//            }
//            //生成jpeg图片
//
//            return sb.toString();
//        } catch (Exception e) {
//            return null;
//        }
    }
    
    public static String encodeBase64_2(String data) {
        StringBuffer sb = new StringBuffer();

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    // b[i]+=256;
                    sb.append(b[i] + 256);
                   
                } else {
                    sb.append(b[i]).append(" ");
                }
                
                 if(i%2!=0){
                     sb.append(",");
                    }
                 else{
                 sb.append(" ");
                 }
                // System.out.println(b[i]);
            }
            //生成jpeg图片

            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }

}
